package algorithm.leetcode;

public class Num141 {
    public static void main(String[] args) {
        ListNode head = new ListNode(3);
        ListNode head_1 = new ListNode(2);
        ListNode head_2 = new ListNode(0);
        ListNode head_3 = new ListNode(-4);
        head.next = head_1;
        head_1.next = head_2;
        head_2.next = head_3;
        head_3.next = head_1;
        System.out.println(hasCycle(head));
    }

    public static boolean hasCycle(ListNode head) {
        if (head == null) return false;
        ListNode fast = head, slow = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
